﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
using Commons;
using Core;
using EntityFramework;
using Hangfire;
using Hangfire.MySql.Core;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http.Features;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.PlatformAbstractions;
using NLog.Extensions.Logging;
using NLog.Web;
using Swashbuckle.AspNetCore.Swagger;
using WebApp.Serivces;

namespace WebApp
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            //获取数据库连接
            //services.AddDbContext<MyDbContext>(d => d.UseSqlServer(Configuration.GetConnectionString("MyDbConnection")));
            services.AddDbContext<MyDbContext>(d => d.UseMySQL(Configuration.GetConnectionString("MyDbConnection")));

            //自动注册服务   所有需要注入的服务，都需要继承IDependency接口
            //services.AddTransient<IFireServices, FireServices>();
            //添加依赖Scrutor
            services.Scan(
                 x =>
                 {
                     var entryAssembly = Assembly.GetEntryAssembly();
                     var referencedAssemblies = entryAssembly.GetReferencedAssemblies().Select(Assembly.Load);
                     var assemblies = new List<Assembly> { entryAssembly }.Concat(referencedAssemblies);

                     x.FromAssemblies(assemblies)
                        .AddClasses(classes => classes.AssignableTo(typeof(IDependency)))
                            .AsImplementedInterfaces()
                            .WithScopedLifetime();
                 });
            services.AddMvc(options =>
            {
                //配置过滤器
                //options.Filters.Add(new LoginValidateFilterAttribute() { IsCheck = true }); // by type
            });
            //hangfire
            services.AddHangfire(config =>
            {
                config.UseStorage(new MySqlStorage(Configuration.GetConnectionString("MyDbConnection")));//注意，这里使用的是mysql
            });//swagger ui
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new Info
                {
                    Version = "v1",
                    Title = "Wechat接口文档",
                    Description = "RESTful API for Wechat",
                    TermsOfService = "None",
                    Contact = new Contact { Name = "ykr", Email = "ykr.yankunru@outlook.com", Url = "" }
                });

                //Set the comments path for the swagger json and ui.
                var basePath = PlatformServices.Default.Application.ApplicationBasePath;
                var xmlPath = Path.Combine(basePath, "WebApp.xml");
                c.IncludeXmlComments(xmlPath);

                //  c.OperationFilter<HttpHeaderOperation>(); // 添加httpHeader参数
            });
            services.Configure<FormOptions>(x => {

                x.ValueLengthLimit = int.MaxValue;
                x.MultipartBodyLengthLimit = int.MaxValue;

            });
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            MyConfigurationSection.SetAppSetting(Configuration.GetSection("WeChat"));

            if (env.IsDevelopment())
            {
                app.UseBrowserLink();
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            //注册hangfire
            app.UseHangfireServer();
            app.UseHangfireDashboard();

            //注册NLog
            loggerFactory.AddNLog();
            //加载NLog配置文件
            env.ConfigureNLog("nlog.config");
            app.UseMvc();
            app.UseStaticFiles();

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");

            });
            // Enable middleware to serve generated Swagger as a JSON endpoint.
            app.UseSwagger();
            // Enable middleware to serve swagger-ui (HTML, JS, CSS etc.), specifying the Swagger JSON endpoint.
            app.UseSwaggerUI(c =>
            {
                c.SwaggerEndpoint("/swagger/v1/swagger.json", "Wechat API V1");
            });
        }
    }
}
